package com.teamin.service.impl;

import com.mysql.cj.core.util.StringUtils;
import com.teamin.mapper.ProgressMapper;
import com.teamin.service.ProgressService;
import com.teamin.service.UserService;
import com.teamin.vo.CircleLabelsVO;
import com.teamin.vo.CircleProgressSecondVO;
import com.teamin.vo.CircleProgressVO;
import com.teamin.web.common.exception.DataException;
import com.teamin.web.common.exception.NotBelongCircleException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ProgressServiceImpl implements ProgressService {

    @Autowired
    private ProgressMapper progressMapper;

    @Autowired
    private UserService userService;

    /**
     * @Author: yangrui
     * @Description: 查看圈子所有任务的标签
     * @Date: 下午6:27 2017/11/24
     */
    @Override
    public List<CircleLabelsVO> labels(Long loginUserId, Integer circleId) {
        // 不属于圈子
        if (!userService.userInCircle(loginUserId, Long.valueOf(circleId))) {
            throw new NotBelongCircleException();
        }
        return progressMapper.labels(circleId);
    }

    /**
     * @Author: yangrui
     * @Description: 进展
     * @Date: 下午7:33 2017/11/24
     */
    @Override
    public CircleProgressVO progress(Long loginUserId, Integer circleId, String labelIds) {
        // 不属于圈子
        if (!userService.userInCircle(loginUserId, Long.valueOf(circleId))) {
            throw new NotBelongCircleException();
        }

        List<Integer> list = new ArrayList<>();
        if (!StringUtils.isNullOrEmpty(labelIds)) {
            String[] labelArr = labelIds.split(",");
            for (String str : labelArr) {
                list.add(Integer.valueOf(str));
            }
            // 标签不匹配
            if (!isMatch4label(list)) {
                throw new DataException();
            }
        }

        CircleProgressVO circleProgressVO = progressMapper.progressWhole(circleId, list);
        List<CircleProgressSecondVO> circleProgressSecondVOList = progressMapper.progressPersonal(circleId, list);
        if (circleProgressSecondVOList != null && circleProgressSecondVOList.size() > 0) {
            circleProgressSecondVOList.stream().forEach(object -> {
                CircleProgressSecondVO vo = object;
                if (!StringUtils.isNullOrEmpty(vo.getNickName())) {
                    vo.setUserName(vo.getNickName());
                }
            });
        }
        circleProgressVO.setCircleProgressSecondVOList(circleProgressSecondVOList);
        return circleProgressVO;
    }

    /**
     * 判断匹配到到数量是否与查出来到数量保持一致
     *
     * @param list
     * @return
     */
    private boolean isMatch4label(List<Integer> list) {
        Integer matchCount = this.progressMapper.labelMatch(list);
        return list.size() == matchCount;
    }
}
